import {ProCard} from '@ant-design/pro-components';
import {
  PageContainer,
} from '@ant-design/pro-components';
import {Avatar, message, SelectProps} from 'antd';
import React, {useEffect, useRef, useState} from 'react';

import AdvancedSearch from "@/pages/platform/components/AdvancedSearch";
import { Space, Table, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {getKuaishouPageUsingPOST} from "@/services/datafa-backend/kuaishouController";
import { Spin } from 'antd';


// BilibiliTableList
const KuaishouTableList: React.FC = () => {
  const [data, setData] = useState<API.KuaishouVO[]>([]);
  const [total, setTotal] = useState<number>(0);
  const currentPage = useRef(1);
  const searchText = useRef<string>();
  const [loading, setLoading] = useState(false);

  const tagsRef = useRef<string[]>();
  const fanRef = useRef<any>();
  const zanRef = useRef<any>()
  const commentRef = useRef<any>();
  const shareRef = useRef<any>();
  const dataStringRef = useRef<[string, string] | string>();

  const columns: ColumnsType<API.BilibiliVO> = [
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      render: (url) => <Avatar src={url} />,
    },
    {
      title: 'nickname',
      dataIndex: 'nickname',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '新发布作品数',
      dataIndex: 'newPost',
      key: 'new_post',
    },
    {
      title: '分享数',
      dataIndex: 'share',
      key: 'share',
    },
    {
      title: '评论数',
      dataIndex: 'comment',
      key: 'comment',
    },
    {
      title: '点赞数',
      dataIndex: 'zan',
      key: 'zan',
    },
    {
      title: '粉丝数',
      dataIndex: 'fan',
      key: 'fan',
    },
    {
      title: '类型',
      key: 'types',
      dataIndex: 'types',
      render: (_, { types }) => (
        <>
          {types?.map((tag) => {
            let color = tag.length > 5 ? 'geekblue' : 'green';
            if (tag === 'loser') {
              color = 'volcano';
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a href={`/#/up/info/kuaishou/${record.id}`}> 查看详情 </a>
        </Space>
      ),
    },
  ];





  const loadData = async (queryRequest: API.BilibiliQueryRequest) => {
    try {
      queryRequest.current = currentPage.current;
      queryRequest.searchText = searchText.current;
      queryRequest.types = tagsRef.current;
      queryRequest.fan = fanRef.current;
      queryRequest.zan = zanRef.current;
      queryRequest.comment = commentRef.current;
      queryRequest.share = shareRef.current;
      queryRequest.startDate = dataStringRef.current?.[0];
      queryRequest.endDate = dataStringRef.current?.[1];
      setLoading(true);
      const res: API.BaseResponsePageKuaishouVO_ = await getKuaishouPageUsingPOST(queryRequest);
      if (res.code === 0) {
        message.success("获取列表成功");
        if (res.data === null) {
          return;
        }
        setData(res.data?.records || []);
        setTotal(res.data?.total || 0)
        setLoading(false);
      } else {
        message.error("获取列表失败");
        setLoading(false);
      }
      return;
    } catch (error) {
      message.error("系统错误");
      setLoading(false);
    }
  }


  /**
   * @zh-CN 开始搜索
   *
   * @param query
   * @param options
   * @param fan
   * @param zan
   * @param comment
   * @param dataString
   * @param share
   */
  const onSearch = async (query: string, options: string[],fan: number, zan: number, comment: number, dataString: [string, string] | string, share: number) => {
    //alert(query)
    searchText.current = query;
    console.log(options ,fan, zan, comment, dataString, share);
    tagsRef.current = options;
    fanRef.current = fan;
    zanRef.current = zan;
    commentRef.current = comment;
    dataStringRef.current = dataString;
    shareRef.current = share;
    currentPage.current = 1;
    const queryRequest: API.BilibiliQueryRequest = {
      "searchText": query,
      "share": share,
      "comment": comment,
      "zan": zan,
      "fan": fan,
      "types": options,
      "current": currentPage.current,
      "pageSize": 10
    };
    await loadData(queryRequest);
  };

  const onRefChange = (num1: any, num2: any, num3: any, options: any) => {
    console.log(num1, num2, num3, options)
  }

  const onChange = (page: number, pageSize: number) => {
    currentPage.current = page;
    console.log(page, pageSize)
    loadData({}).then()
  }

  useEffect(() => {
    // @ts-ignore
    loadData({}).then(r =>{})
  }, data)


  const tagsKuaishou = ["搞笑","情感","美食","娱乐","游戏","萌宠","才艺","健康","运动","旅游","二次元","时尚","母婴","教育","汽车","家居","科技","文化","生活"]
  const optionsProp: SelectProps['options'] = []
  for (let i = 0; i < tagsKuaishou.length; i++) {
    optionsProp.push({
      label: tagsKuaishou[i],
      value: tagsKuaishou[i],
    });
  }


  return (
    <PageContainer>
        <ProCard direction="column" ghost gutter={[0, 8]}>

          <ProCard colSpan={24} layout="center" bordered>
            <AdvancedSearch onSearch={onSearch} onRefChange={onRefChange} options={optionsProp}  />
          </ProCard>
          <Spin spinning={loading}>
            <Table
              style={{width: '100%'}}
              columns={columns}
              dataSource={data}
              pagination={{
                defaultCurrent: 1,
                total: total,
                pageSize: 10, /*每页条数：如果不配置的话，默认是每页20条显示*/
                showTotal: () => `共${total}条`, /*总条数的展示*/
                position: ["bottomRight"],
                onChange
              }}
            />
          </Spin>

          {/*<ProCard style={{width:"100%"}} layout="center" bordered>*/}
          {/*  */}
          {/*</ProCard>*/}

        </ProCard>


    </PageContainer>
  );
};
export default KuaishouTableList;
